#!/bin/bash
#
# this shell work for servercheck
# add this shell to crontal 
# */5 * * * * /data/shell/server_check.sh 8080 >> /data/logs/server_check.log 2>&1 &


PORT=$1

case "$1" in

    8080)

        server_name="hellonode"
        driver="/usr/local/bin/node"
        script="/home/yoft/hellonode.js"
        argv=""

    ;;

    8081)

        server_name="pyproxy"
        driver="/usr/local/bin/python"
        script="/home/yoft/pyproxy.py"
        argv="8081"

    ;;

    *)

        echo "Unknow server on $1"
        exit 1

    ;;

esac

function start_server()
{

    echo "Server[$server_name] start..."
    $driver $script $argv >> ${script}.log 2>&1 &
}

function start_server()
{

    echo "Server[$server_name] start..."
    $driver $script $argv >> ${script}.log 2>&1 &
}

function restart_server()
{
    PID=`ps aux|grep $server_name |grep -v "grep"|awk '{print $2}'`
    echo "Server pid[$PID] already exists, but server was falied!"
    echo "Server[$server_name] restart..."
    kill -TERM $PID
    start_server
}

function check()
{
    #getHttpCode
    retCode=`curl -o /dev/null -s -w "%{http_code}" http://127.0.0.1:$PORT/`

    if [ "$retCode"1 -eq "000"1 ];then
        echo Server on \"127.0.0.1:$PORT\" was closed!
        start_server
    fi

    if [ "$retCode"1 -ge "500"1 ];then
        echo Server on \"127.0.0.1:$PORT\" was failed!
        restart_server
    fi
}

check

exit 0